package blog.service.impl;

import blog.dao.pojo.SysUser;
import blog.service.RegisterService;
import blog.service.SysUserService;
import blog.utils.JwtUtils;
import blog.vo.ErrorCode;
import blog.vo.Result;
import blog.vo.params.LoginParam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String salt = "vs3dv$$#%";

    // 注册新用户
    @Override
    public Result register(LoginParam loginParam) throws JsonProcessingException {

        // 验证传过来的信息是否完整
        if (loginParam.getPassword()==null||loginParam.getAccount()==null||loginParam.getNickname()==null)
            return Result.fail(-9999,"注册信息不完整");

        SysUser sysUser = sysUserService.findUserByAccount(loginParam.getAccount());

        // 账号已存在
        if (sysUser!=null) return Result.fail( ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());

        // 开始创建新用户
        SysUser newUser = new SysUser();
        newUser.setAccount(loginParam.getAccount());
        newUser.setNickname(loginParam.getNickname());
        newUser.setCreateDate(System.currentTimeMillis());
        newUser.setLastLogin(System.currentTimeMillis());
        newUser.setAvatar("/static/img/logo.b3a48c0.png");
        newUser.setAdmin(1); //1 为true
        newUser.setDeleted(0); // 0 为false
        newUser.setSalt("");
        newUser.setStatus("");
        newUser.setEmail("");

        String pwd = DigestUtils.md5Hex(loginParam.getPassword()+salt); // 加密后的密码放入数据库
        newUser.setPassword(pwd);
        newUser.setAvatar("/static/img/logo.b3a48c0.png");

        sysUserService.save(newUser); // 保存新用户

        // 生成token, 存到 redis
        String token = JwtUtils.createToken(newUser.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token,new ObjectMapper().writeValueAsString(newUser));

        return Result.success(token);
    }
}
